import { Breadcrumb, Button, Form, Input, Select, Upload, Radio, message } from 'antd';
import { PlusOutlined } from '@ant-design/icons';
import { Link, useSearchParams } from 'react-router-dom';
import { useEffect, useState } from "react";
import { createArticleAPI, getArticleByIdAPI, updateArticleAPI } from "@/apis/article";
import './index.scss';
// 富文本插件
import ReactQuill from "react-quill";
import "react-quill/dist/quill.snow.css";
import { useChannel } from '@/hooks/useChannel';

const { Option } = Select;
const Publish = () => {
      // 获取频道列表
      const { channelList } = useChannel()
      // 提交表单
      const onFinish = (formValue) => {
            const { title, channel_id, content, type } = formValue
            // 校验封面类型imageType是否和实际的图片列表imageList数量是相等的
            if (imageList.length !== imageType) return message.warning('封面类型和图片数量不匹配')
            // 1.按照接口文档的格式处理收集到的表单数据
            const params = {
                  title,
                  channel_id,
                  content,
                  cover: {
                        type, //封面模式
                        images: imageList.map(item => {
                              if (item.response) {
                                    return item.response.data.url
                              } else {
                                    return item.url
                              }
                        }),//图片列表
                  }
            }
            // 2.调用接口提交
            // 处理调用不同接口 新增 - 新增接口 编辑 - 更新接口 id
            if (articleId) {
                  // 更新接口
                  updateArticleAPI({ ...params, id: articleId })
            } else {
                  createArticleAPI(params)
            }
      }


      // 上传回调
      const [imageList, setImageList] = useState([])
      const onUploadChange = (value) => {
            console.log('正在上传中', value);
            setImageList(value.fileList)
      }


      // 切换图片封面类型
      const [imageType, setImageType] = useState(0)
      const onTypeChange = (e) => {
            setImageType(e.target.value)
      }

      // 回填数据
      //useSearchParams 用来匹配URL中?后面的搜索参数，所以仅仅只能用于？传参的形式
      const [searchParams] = useSearchParams()
      const articleId = searchParams.get('id');
      // 获取Form实例
      const [form] = Form.useForm();
      useEffect(() => {
            // 1.通过id获取数据
            async function getArticleDetail() {
                  const res = await getArticleByIdAPI(articleId)
                  const data = res.data
                  const { cover } = data
                  form.setFieldsValue({
                        ...data,
                        // 数据结构的问题 set方法=>{type:3} {cover:{type:3}}
                        type: cover.type,
                  })
                  setImageType(cover.type)
                  // 显示图片->数据格式问题{url:url}
                  setImageList(cover.images.map(url => {
                        return { url }
                  }))
            }
            // 只有编辑有id的时候才能调用此函数
            if (articleId) {
                  getArticleDetail()
            }
      }, [articleId, form])
      return (

            <div className="publish">
                  <Breadcrumb
                        items={[
                              { title: <Link to={'/'}>首页</Link> },
                              { title: articleId ? '编辑文章' : '发布文章' },
                        ]} />
                  <Form form={form} onFinish={onFinish} labelCol={{ span: 4 }} wrapperCol={{ span: 16 }} initialValues={{ type: 0 }}>
                        <Form.Item name="title" label="标题" rules={[{ required: true, message: "请输入文章标题" }]} >
                              <Input style={{ width: 400 }} placeholder="请输入文章标题" />
                        </Form.Item>

                        <Form.Item name="channel_id" label="频道" rules={[{ required: true, message: "请选择文章频道" }]} >
                              <Select placeholder="请选择文章频道" style={{ width: 400 }} allowClear>
                                    {/* vlaue属性用户选中之后会自动收集起来作为接口的提交字段 */}
                                    {channelList.map((item) => {
                                          return (
                                                <Option value={item.id} key={item.id}>{item.name}</Option>
                                          )
                                    })}
                              </Select>

                        </Form.Item>

                        <Form.Item name="cover" label="文章封面">
                              <Form.Item name="type">
                                    <Radio.Group onChange={onTypeChange}>
                                          <Radio value={1}>单图</Radio>
                                          <Radio value={3}>三图</Radio>
                                          <Radio value={0}>无图</Radio>
                                    </Radio.Group>
                              </Form.Item>
                              {imageType > 0 &&
                                    <Upload
                                          listType="picture-card"//上传列表的内建样式
                                          showUploadList//是否展示文件列表
                                          action={'http://geek.itheima.net/v1_0/upload'}//上传的地址
                                          name='image' //发到后台的文件参数名
                                          maxCount={imageType} //限制数量
                                          fileList={imageList}
                                          onChange={onUploadChange}
                                    >
                                          <div style={{ marginTop: 8 }}>
                                                <PlusOutlined />
                                          </div>
                                    </Upload>
                              }
                        </Form.Item>

                        {/* 富文本编辑器 */}
                        <Form.Item name="content" label="内容" rules={[{ required: true, message: "请输入文章内容" }]} >
                              <ReactQuill className='publish-quill' theme='snow' placeholder='请输入文章内容' />
                        </Form.Item>

                        <Form.Item wrapperCol={{ offset: 4 }}>
                              <Button type="primary" htmlType="submit">
                                    发布文章
                              </Button>
                        </Form.Item>
                  </Form>
            </div>
      )
}

export default Publish;